package com.xidian.zhiancloud.service.chemicalsManagement.chemicalManager.wastePart;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.constant.DangerousManagementConstant;
import com.xidian.zhiancloud.dao.WasteInfoMapper;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.WasteInfo;
import com.xidian.zhiancloud.model.WasteType;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.chemicalsManagement.WasteInfoQO;
import com.xidian.zhiancloud.vo.chemicalsManagement.WasteInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: Egoist
 * @Date: 2020/11/10 17:00
 */

@Service
public class WasteInfoService extends ServiceImpl<WasteInfoMapper, WasteInfo> implements IService<WasteInfo> {

    @Autowired
    private WasteInfoMapper wasteInfoMapper;
    @Autowired
    private WasteTypeService wasteTypeService;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    public IPage<WasteInfoVO> getListByQueryObject(WasteInfoQO wasteInfoQO) {
        Page<WasteInfoVO> page = new Page<>(wasteInfoQO.getCurrent(), wasteInfoQO.getSize());
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn("create_time").setAsc(false);
        page.getOrders().add(orderItem);

        IPage<WasteInfoVO> iPage = wasteInfoMapper.getListByQO(page, wasteInfoQO);
        List<WasteInfoVO> records = iPage.getRecords();
        List<WasteInfoVO> ans = new ArrayList<>();
        records.forEach(t -> {
            if (t.getRealQuantity() == null) {
                t.setRealQuantity(new BigDecimal(0));
            }
            t.setStrMaxQuantity(t.getMaxQuantity().toString() + DangerousManagementConstant.QuantityUnit.get(t.getUnit()));
            t.setStrRealQuantity(t.getRealQuantity().toString() + DangerousManagementConstant.QuantityUnit.get(t.getUnit()));
            ans.add(t);
        });
        iPage.setRecords(ans);
        return iPage;
    }

    public WasteInfoVO getVOById(Long id) {
        WasteInfo wasteInfo = getById(id);
        if (wasteInfo == null) {
            throw new CustomizeException(GeneralResponseEnums.GET_FAILED);
        }
        WasteInfoVO wasteInfoVO = new WasteInfoVO();
        BeanUtils.copyProperties(wasteInfo, wasteInfoVO);
        Long typeId = wasteInfo.getTypeId();
        Long organizationId = wasteInfo.getOrganizationId();
        Long managerId = wasteInfo.getManagerId();

        WasteType wasteType = wasteTypeService.getById(typeId);
        Organization organization = organizationMapper.selectById(organizationId);
        SysUser sysUser = sysUserMapper.selectById(managerId);
        wasteInfoVO.setWasteType(wasteType == null ? "该类型已删除" : wasteType.getWasteType());
        wasteInfoVO.setDepartmentName(organization == null ? "该部门已删除" : organization.getName());
        wasteInfoVO.setManagerName(sysUser == null ? "该员工已删除" : sysUser.getName());
        return wasteInfoVO;
    }

    public Map<Long, String> getName(Long companyId) {
        LambdaQueryWrapper<WasteInfo> queryWrapper = new LambdaQueryWrapper<WasteInfo>();
        queryWrapper.eq(WasteInfo::getCompanyId, companyId);
        List<WasteInfo> wasteInfos = wasteInfoMapper.selectList(queryWrapper);
        return wasteInfos.stream().collect(Collectors.toMap(WasteInfo::getId, WasteInfo::getWasteName));

    }

    public ResultDTO<Boolean> saveInfo(WasteInfo wasteInfo) {
        QueryWrapper<WasteInfo> query = new QueryWrapper<>();
        query.eq("company_id", wasteInfo.getCompanyId());
        List<WasteInfo> list = list(query);
        if (list != null) {
            for (WasteInfo info : list) {
                if (info.getWasteName().equals(wasteInfo.getWasteName())) {
                    return ResultDTO.errorOf(-1, info.getWasteName() + " 已存在!");
                }
            }
        }
        return ResultDTO.successOf(save(wasteInfo), GeneralResponseEnums.SUCCESS);
    }

    public ResultDTO<Boolean> updateByIdCheckName(WasteInfo wasteInfo, Long companyId) {
        QueryWrapper<WasteInfo> query = new QueryWrapper<>();
        query.eq("company_id", companyId);
        List<WasteInfo> list = list(query);
        String wasteName = wasteInfo.getWasteName();
        for (WasteInfo info : list) {
            //如果修改记录与库内记录的品名相同 并且 修改记录与库内记录不是同一条时 发生重名错误
            if (wasteName != null && wasteName.equals(info.getWasteName()) &&
            !info.getId().equals(wasteInfo.getId())) {
                return ResultDTO.errorOf(-1, wasteName + " 已存在!");
            }
        }
        return ResultDTO.successOf(updateById(wasteInfo), GeneralResponseEnums.SUCCESS);
    }

    public String getUnitByName(String name) {
        QueryWrapper<WasteInfo> query = new QueryWrapper<WasteInfo>();
        query.eq("waste_name", name);
        WasteInfo info = getOne(query);
        return DangerousManagementConstant.QuantityUnit.get(info.getUnit());
    }

    public ResultDTO<Map<String, String>> getInfoById(Long wasteId, Long userId) {
        WasteInfo info = getById(wasteId);
        if (info == null) {
            return ResultDTO.errorOf(GeneralResponseEnums.SUCCESS);
        }
        Map<String, String> map = new HashMap();
        map.put("unit", DangerousManagementConstant.QuantityUnit.get(info.getUnit()));
        map.put("wasteType", wasteTypeService.getById(info.getTypeId()).getWasteType());
        map.put("outer", sysUserMapper.selectById(userId).getName());
        return ResultDTO.successOf(map,GeneralResponseEnums.SUCCESS);
    }
}
